package com.project.common.Security;

import cn.hutool.json.JSONUtil;
import com.project.entity.Users;
import com.project.service.UsersService;
import com.project.util.JwtUtils;
import com.project.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private UsersService usersService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)
            throws IOException, ServletException {
        // 设置响应编码
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        // 获取输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        // 拿到authentication中的用户名信息
        String username = authentication.getName();
        // 利用用户名信息生成token数据
        String token = JwtUtils.genJwtToken(username);
        // 根据用户名查询获得当前用户的信息
        Users currentUser = usersService.getByUsername(username);
        // 设置响应数据
        outputStream.write(JSONUtil.toJsonStr(
                R.ok("登录成功")
                        .put("authorization", token)
                        .put("currentUser", currentUser)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}
